package felix.things.router.mqtt.server.auth.service;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import felix.things.router.mqtt.server.common.auth.IAuthService;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.security.interfaces.RSAPrivateKey;

/**
 * 用户名和密码认证服务
 *
 * @author Felix
 * @date 2019/8/21
 */
@Service
public class AuthServiceImpl implements IAuthService {

    private RSAPrivateKey privateKey;

    @Override
    public boolean checkValid(String clientIp, String username, String password) {
        // 本机免密登录
        if ("127.0.0.1".equals(clientIp)) {
            return true;
        }
        if (StrUtil.isBlank(username)) {
            return false;
        }
        if (StrUtil.isBlank(password)) {
            return false;
        }
        RSA rsa = new RSA(privateKey, null);
        String value = rsa.encryptBcd(username, KeyType.PrivateKey);
        return value.equals(password);
    }

    @PostConstruct
    public void init() {
        privateKey = IoUtil.readObj(AuthServiceImpl.class.getClassLoader().getResourceAsStream("keystore/auth-private.key"));
    }

}
